package com.no1.musicmgr.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImgCodeUtil {

    /**
     * 将字符串转换为图片并保存到指定路径。
     *
     * @param text       需要转换的字符串
     * @param outputPath 图片保存的路径
     */
    public static void convertStringToImage(String text, String outputPath) {
        int width = 200;
        int height = 100;

        // 创建 BufferedImage 对象，用于绘制文字
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        // 设置背景色和字体
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.BLACK);
        Font font = new Font("Arial", Font.BOLD, 20);
        g2d.setFont(font);

        // 绘制字符串
        FontMetrics fm = g2d.getFontMetrics();
        int x = (width - fm.stringWidth(text)) / 2; // 居中文字
        int y = (fm.getAscent() + (height - (fm.getAscent() + fm.getDescent())) / 2); // 居中文字
        g2d.drawString(text, x, y);

        // 释放资源
        g2d.dispose();

        // 确保输出目录存在
        File outputFile = new File(outputPath);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs(); // 创建目录
        }

        // 保存图片
        try {
            ImageIO.write(bufferedImage, "png", outputFile);
            System.out.println("Image has been created successfully and saved to: " + outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
